<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        width: 100px;
        height: 100px;
        position: absolute;
        left: 0px;
        top: 0px;
        background: red;
      }
    </style>
  </head>

  <body>
    <div class="box"></div>
  </body>
  <script>
    function move(ele, target, dir) {
        return new Promise(resolve => {
            function fn() {
                let startLeft = parseInt(getComputedStyle(ele, null)[dir]);
                // console.log(startLeft)
                // let speed =(target-startLeft)/ Math.abs( target-startLeft ) ;
                let speed = (target - startLeft) > 0 ? 1 : -1;
                setTimeout(() => {
                    startLeft += speed;
                    if (startLeft === target) {
                        // console.log("运动完成");
                        // cb && cb();
                        resolve("运动完成");
                    } else {
                        ele.style[dir] = startLeft + "px";
                        fn();
                    }
                }, 10);
            }
            fn();
        })
    }

    // requestAnimationFrame
    // let ele = document.querySelector(".box");
    // move(ele, 300, "left").then(res=>{
    //     console.log(res);
    //   return  move(ele, 300, "top");
    // }).then(res=>{
    //     console.log(res);
    //     return move(ele, 0, "left");
    // }).then(res=>{
    //     return  move(ele, 0, "top");
    // }).then(res=>{
    //     console.log("所有运动完毕");
    // })

    // 作业：通过async及await改造方块动画执行； 暗号:扇子
    let ele = document.querySelector(".box");
    async function asyncMove() {
      try {
        await move(ele, 300, "left");
        await move(ele, 300, "top");
        await move(ele, 0, "left");
        await move(ele, 0, "top");
      } catch (e) {
        console.log(e);
      }
    }
    asyncMove();
  </script>
</html>
